<?php

//! xml premenne
// data
// queryError
// sessionId
// logged
// queryResult

function connect( & $connection )
{
    $connection = mysql_connect( "localhost", "root", "" );
    if (! $connection)
        return false;

    mysql_select_db( "regdatabase", $connection );
    return true;
}

function executeDml( & $xmlData, $sqlQuery )
{
    $result = mysql_query( $sqlQuery );
    if (! $result)
    {
        $xmlData['queryError'] = "mysql_query failed by Dml statement";
        return false;
    }

    return true;
}

function executeSelect( & $xmlData, $sqlQuery )
{
    $result = mysql_query( $sqlQuery );
    if (! $result)
    {
        $xmlData['queryError'] = "mysql_query failed by select statement";
        return false;
    }
    
    // riadky su oddelene znakom |, stlpce znakom ; a par hodnot, ci je to null znakom :
    $resultStr = "";
    while ($row = mysql_fetch_array( $result, MYSQL_NUM ))
    {
        foreach ($row as $value)
        {
            if (is_null( $value ))
            {
                $resultStr .= "1: ;";
            }
            else
            {
                $resultStr .= "0:" . base64_encode( $value ) . ";";
            }
    }
        
        $resultStr .= "|";
    }
    
    $xmlData['queryResult'] = $resultStr;
    mysql_free_result( $result );
    return true;
}

function loginUser( $login, $password )
{
    if (! isset( $login ) || ! isset( $password ) )
        return false;
    
    // toto vymenim za login z databazy
    if ($login=="martin" && $password == "mozi")
        return true;
    
    try 
    {
        $dbPdo = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
        $sqlStatement = $dbPdo->prepare( "SELECT userId FROM users WHERE login = :login AND password = :password" );

        $sqlStatement->bindValue( ':login', $login, PDO::PARAM_STR );
        $sqlStatement->bindValue( ':password', $password, PDO::PARAM_STR );
        $sqlStatement->execute();
        
        foreach ($dbPdo->query($sqlStatement) as $row)
        {
            // mozno z riadku vytiahnem $row['userid']
            return true;
        }
    }
    catch(PDOException $e)
    {
        // echo $e->getMessage();
    }
    
    /*** close the database connection ***/
    $dbPdo = null;
    return false;
}

function outXmlData( & $xmlData )
{
    // nie je definovane poradie vystupnych dat
    $xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    $xmlString .= "<data>";
    foreach ($xmlData as $key => $value)
    {
        if (is_integer( $key ))
           continue;
    
        $xmlString .= "<" . $key . ">" . $value . "</" . $key . ">";  
    }

    $xmlString .= "</data>";
    echo( base64_encode( $xmlString ) );
}

function startSessionFromId( & $xmlData )
{
    if (isset($_POST[ 'sessionId' ])) 
    {
        $idSession = $_POST['sessionId'];
        session_id( $idSession );
        session_start();
        $xmlData['sessionId'] = $idSession;
    } 
    else 
    {
        session_start();
        $idSession = session_id();
        // nemam session muselo prist meno a heslo
        if (isset( $_POST['login'] ) && isset( $_POST['password'] ))
        {   
            $login = $_POST['login'];
            $password = $_POST['password'];
            if (loginUser( $login, $password ))
            {
                $_SESSION['adminlogged'] = true;
                $xmlData['sessionId'] = $idSession;
            }
            else
            {
                $xmlData['logged'] = 4;
                unset( $_SESSION['adminlogged'] );
                return false;
            }
        }
        else
        {
            $xmlData['logged'] = 0;
            unset( $_SESSION['adminlogged'] );
            return false;
        }
    }

    return true;
}

function runAdmin( & $xmlData )
{
    if (! isset($_SESSION['adminlogged']))
    {
        // vyprsala platnost session
        $xmlData['logged'] = "2";
        return false;
    }

    $xmlData['logged'] = 1;    
    if (! isset( $_POST[ 'queryType' ] ) || ! isset( $_POST[ 'sqlQuery' ] ))
    {
        $xmlData['queryError'] = "Query type or sql query not set";
        return false;
    }

    $connection = null;
    if (! connect( $connection ))
    {
        $xmlData['queryError'] = "Connection error";
        return false;
    }

    $returnValue = false;
    $sqlString = base64_decode( $_POST[ 'sqlQuery' ] );
    switch ($_POST[ 'queryType' ])
    {
        case 0: // Select
            $returnValue = executeSelect( $xmlData, $sqlString );
            break;
        
        case 1: // DML
            $returnValue = executeDml( $xmlData, $sqlString );
            break;
        
        default:
            $xmlData['queryError'] =  "Unknown queryType";
            $returnValue = false;
            break;
    }

    mysql_close( $connection );
    return $returnValue;
}

$xmlData = array();
if (startSessionFromId( $xmlData ))
{
    runAdmin( $xmlData );
}

outXmlData( $xmlData );
?>
